package com.example.dzbsh.controller;


import com.example.dzbsh.model.Fujian;
import com.example.dzbsh.service.FujianService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@RestController
@RequestMapping("fujian")
public class FujianController {

    @Resource
    FujianService ddService;

    @Value("./userfiles")
    String userfilepath;

    private Logger logger = LoggerFactory.getLogger(getClass());

    @RequestMapping("findfile")
    public void findfile(HttpServletRequest request,
                         HttpServletResponse response,
                         @RequestParam("id") String ppId){
        try {
            //根据附件ID取的附件信息

            Fujian mmFujian = ddService.selectByPrimaryKey(ppId);
            if(mmFujian == null) {
                throw new RuntimeException("不存在该附件信息！");
            }
            String url = mmFujian.getNewfilename();
            // 获取项目根目录地址,并去除最后斜杠
            if(userfilepath.endsWith("/")){
                userfilepath  = userfilepath.substring(0, userfilepath.length()-1);
            }

            /*System.out.println(userfilepath+ url);*/
            // 将附件返回前台
            reutrnfile(userfilepath + url,mmFujian.getNewfilename(),request,response);

        }catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static void reutrnfile(String filepath,String newfilename,
                                  HttpServletRequest request,HttpServletResponse response) throws IOException {
        ServletOutputStream out = null;
        FileInputStream ips = null;
        try {

            // 获取文件存放的路径
            File file = new File(filepath);
            if (!file.exists()) {
                // 如果文件不存在就跳出
                return;
            }
            ips = new FileInputStream(file);
            response.setContentType("multipart/form-data");
            // 为文件重新设置名字，采用数据库内存储的文件名称
            response.addHeader("Content-Disposition", "attachment; filename=\""
                    + new String(newfilename.getBytes("UTF-8"), "ISO8859-1")
                    + "\"");
            out = response.getOutputStream();
            // 读取文件流
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = ips.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
            ips.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
